<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import { getCategoryList, categorySwitch, categoryBatch } from '@/api/backend/category';
import { useToast } from 'primevue/usetoast';

const isLoading = ref(false);
const toast = useToast();
const treeTableValue = ref(null);
const categoryDialog = ref(false);
const deleteCategoryDialog = ref(false);
const deleteCategoriesDialog = ref(false);
const category = ref({});
const submitted = ref(false);
const selectedCategories = ref();
const categoryTypes = ref([
    { label: '链接', value: -2 },
    { label: '单页', value: -1 },
    { label: '文章模型', value: 1 },
    { label: '产品模型', value: 2 },
    { label: '招聘模型', value: 3 }
]);
const getModelType = (type) => {
    if (type === -2) return '链接';
    if (type === -1) return '单页';
    if (type === 1) return '文章模型';
    if (type === 2) return '产品模型';
    if (type === 3) return '招聘模型';
    return '未知类型';
};
const changeBlank = async (data) => {
    const { code } = await categorySwitch({
        cate_id: data.cate_id,
        type: 2,
        state: data.is_blank ? 0 : 1
    });
    if (code === 200) {
        await loadContent();
        showSuccess('操作成功');
    }
};
const changeStatus = async (data) => {
    const { code } = await categorySwitch({
        cate_id: data.cate_id,
        type: 1,
        state: data.status ? 0 : 1
    });
    if (code === 200) {
        await loadContent();
        showSuccess('操作成功');
    }
};
function editCategory(prod) {
    category.value = { ...prod };
    categoryDialog.value = true;
}

function confirmDeleteCategory(prod) {
    category.value = prod;
    deleteCategoryDialog.value = true;
}
function deleteCategory() {
    treeTableValue.value = treeTableValue.value.filter((val) => val.data.cate_id !== category.value.cate_id);
    deleteCategoryDialog.value = false;
    category.value = {};
    toast.add({
        severity: 'success',
        summary: 'Successful',
        detail: '栏目已删除',
        life: 3000
    });
}
function hideDialog() {
    categoryDialog.value = false;
    submitted.value = false;
}

const showSuccess = (summary, detail = '') => {
    toast.add({ severity: 'success', summary, detail, life: 3000 });
};

const showError = (summary, detail = '') => {
    toast.add({ severity: 'error', summary, detail, life: 3000 });
};

let abortController = null;
const loadContent = async () => {
    try {
        abortController?.abort();
        abortController = new AbortController();

        isLoading.value = true;
        const { code, data } = await getCategoryList();

        if (code === 200) {
            treeTableValue.value = data;
        }
    } catch (error) {
        if (error.name !== 'AbortError') {
            showError('加载失败', error.message);
        }
    } finally {
        isLoading.value = false;
        abortController = null;
    }
};
// 生命周期和监听
onMounted(loadContent);
onUnmounted(() => {
    abortController?.abort();
});

const confirmDeleteSelected = async () => {
    deleteCategoriesDialog.value = true;
};

const deleteSelectedCategories = async () => {
    try {
        const selectedIds = Object.keys(selectedCategories.value)
            .filter((key) => selectedCategories.value[key])
            .map(Number)
            .join(','); // 转为数字类型

        if (selectedIds.length === 0) {
            showError('请先选择要锁定的栏目');
            return;
        }
        console.log({ id: selectedIds, type: 5 });
        return;
        // 调用批量启用 API
        const { code } = await categoryBatch({ id: selectedIds, type: 5 });
        if (code === 200) {
            await loadContent(); // 重新加载数据
            selectedCategories.value = {}; // 清空选中状态
            showSuccess('操作成功');
        }
    } catch (error) {
        showError('删除失败', error.message);
    }
    deleteCategoriesDialog.value = false;
};
const openNew = async () => {
    category.value = {};
    submitted.value = false;
    categoryDialog.value = true;
};
const openAdd = () => {
    window.location.href = '/backend/category/add';
};
function saveCategory() {
    submitted.value = true;
    console.log(category.value);
    submitted.value = false;
}
const items = [
    {
        label: '批量启用',
        command: async () => {
            const selectedIds = Object.keys(selectedCategories.value)
                .filter((key) => selectedCategories.value[key])
                .map(Number)
                .join(','); // 转为数字类型

            if (selectedIds.length === 0) {
                showError('请先选择要启用的栏目');
                return;
            }
            // 调用批量启用 API
            const { code } = await categoryBatch({ id: selectedIds, type: 1 });
            if (code === 200) {
                await loadContent(); // 重新加载数据
                selectedCategories.value = {}; // 清空选中状态
                showSuccess('操作成功');
            }
        }
    },
    {
        label: '批量锁定',
        command: async () => {
            const selectedIds = Object.keys(selectedCategories.value)
                .filter((key) => selectedCategories.value[key])
                .map(Number)
                .join(','); // 转为数字类型

            if (selectedIds.length === 0) {
                showError('请先选择要锁定的栏目');
                return;
            }
            // 调用批量启用 API
            const { code } = await categoryBatch({ id: selectedIds, type: 2 });
            if (code === 200) {
                await loadContent(); // 重新加载数据
                selectedCategories.value = {}; // 清空选中状态
                showSuccess('操作成功');
            }
        }
    },
    {
        separator: true
    },
    {
        label: '批量删除',
        command: async () => {
            confirmDeleteSelected();
        }
    }
];
</script>

<template>
    <div class="card">
        <div class="font-semibold text-xl mb-4">栏目管理</div>
        <Toolbar class="mb-6">
            <template #start>
                <Button label="添加栏目" icon="pi pi-plus" severity="secondary" class="mr-2" @click="openNew" />
                <SplitButton label="批量操作" @click="batch" :model="items" />
                <Button label="更新缓存" icon="pi pi-plus" severity="secondary" class="mr-2" @click="openAdd" />
            </template>
        </Toolbar>
        <TreeTable :value="treeTableValue" selectionMode="checkbox" v-model:selectionKeys="selectedCategories">
            <Column field="cate_name" header="栏目名称" :expander="true" style="white-space: nowrap"></Column>
            <Column field="cate_type" header="模型" style="white-space: nowrap">
                <template #body="data">
                    {{ getModelType(data.node.data.cate_type) }}
                </template>
            </Column>
            <Column field="status" header="导航显示" style="min-width: 12rem">
                <template #body="data">
                    <ToggleSwitch v-model="data.node.data.status" @click="changeStatus(data.node.data)" />
                </template>
            </Column>
            <Column field="is_blank" header="新窗口" style="min-width: 12rem">
                <template #body="data">
                    <ToggleSwitch v-model="data.node.data.is_blank" @click="changeBlank(data.node.data)" />
                </template>
            </Column>
            <Column :exportable="false" style="min-width: 12rem">
                <template #body="data">
                    <Button icon="pi pi-pencil" outlined rounded class="mr-2" @click="editCategory(data.node.data)" />
                    <Button icon="pi pi-trash" outlined rounded severity="danger" @click="confirmDeleteCategory(data.node.data)" />
                </template>
            </Column>
        </TreeTable>
        <Dialog v-model:visible="categoryDialog" :style="{ width: '450px' }" :header="category.cate_id ? '编辑栏目' : '添加栏目'" :modal="true">
            <div class="flex flex-col gap-6">
                <img v-if="category.image" :src="`https://primefaces.org/cdn/primevue/images/category/${category.image}`" :alt="category.image" class="block m-auto pb-4" />
                <div>
                    <label for="cate_name" class="block font-bold mb-3">栏目名称</label>
                    <InputText id="cate_name" v-model.trim="category.cate_name" required="true" autofocus :invalid="submitted && !category.cate_name" fluid />
                    <small v-if="submitted && !category.cate_name" class="text-red-500">栏目名称为必填项.</small>
                </div>
                <div>
                    <label for="cate_type" class="block font-bold mb-3">栏目模型</label>
                    <Select id="cate_type" v-model="category.cate_type" :options="categoryTypes" optionLabel="label" optionValue="value" placeholder="请选择栏目模型" :disabled="submitted" :invalid="submitted && !category.cate_type" />
                    <small v-if="submitted && !category.cate_type" class="text-red-500">栏目模型为必填项.</small>
                </div>
                <div>
                    <label for="parent_id" class="block font-bold mb-3">上级栏目</label>
                    <TreeSelect v-model="category.parent_id" :options="treeTableValue" placeholder="请选择上级栏目" :disabled="submitted" :invalid="submitted && !category.parent_id" />
                </div>
            </div>

            <template #footer>
                <Button label="Cancel" icon="pi pi-times" text @click="hideDialog" />
                <Button label="Save" icon="pi pi-check" @click="saveCategory" />
            </template>
        </Dialog>

        <Dialog v-model:visible="deleteCategoryDialog" :style="{ width: '450px' }" header="删除栏目" :modal="true">
            <div class="flex items-center gap-4">
                <i class="pi pi-exclamation-triangle !text-3xl" />
                <span v-if="category"
                    >确定要删除 <b>{{ category.cate_name }}</b
                    >?</span
                >
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="deleteCategoryDialog = false" />
                <Button label="确定" icon="pi pi-check" @click="deleteCategory" />
            </template>
        </Dialog>
        <Dialog v-model:visible="deleteCategoriesDialog" :style="{ width: '450px' }" header="批量删除" :modal="true">
            <div class="flex items-center gap-4">
                <i class="pi pi-exclamation-triangle !text-3xl" />
                <span v-if="selectedCategories">确定删除选中的栏目吗?</span>
            </div>
            <template #footer>
                <Button label="No" icon="pi pi-times" text @click="deleteCategoriesDialog = false" />
                <Button label="Yes" icon="pi pi-check" text @click="deleteSelectedCategories" />
            </template>
        </Dialog>
    </div>
</template>
